const getStyle = (element, attr, NumberMode = "int") => {
  let target;
  // scrollTop 获取方式不同，没有它不属于style，而且只有document.body才能用
  if (attr === "scrollTop") {
    target = element.scrollTop;
  } else if (element.currentStyle) {
    target = element.currentStyle[attr];
  } else {
    target = document.defaultView.getComputedStyle(element, null)[attr];
  }
  //在获取 opactiy 时需要获取小数 parseFloat
  return NumberMode == "float" ? parseFloat(target) : parseInt(target);
};

export default {
  mounted(el, Binding) {
    let windowHeight: number = window.innerHeight;
    let height: number;
    let offsetTop: number;
    let paddingBottom: number;
    let marginBottom: number;
    let frameId: number;
    let oldScrollTop: number;
    let scrollELE: HTMLElement;
    let heightElE: HTMLElement;
    let scrollType: number = el.attributes.type && el.attributes.type.value;
    let scrollReduce: number = 2;
    if (scrollType == 2) {
      scrollELE = el;
      heightElE = el.children[0];
    } else {
      scrollELE = document.documentElement;
      heightElE = el;
    }
    el.addEventListener(
      "touchstart",
      () => {
        height = heightElE.clientHeight;
        offsetTop = el.offsetTop;
        paddingBottom = getStyle(el, "paddingBottom");
        marginBottom = getStyle(el, "marginBottom");
      },
      false
    );
    el.addEventListener("touchmove", () => {
      loadMore();
    });
    el.addEventListener("touchend", () => {
      oldScrollTop = scrollELE.scrollTop;
      moveEnd();
    });
    const moveEnd = () => {
      frameId = requestAnimationFrame(() => {
        if (scrollELE.scrollTop != oldScrollTop) {
          oldScrollTop = scrollELE.scrollTop;
          moveEnd();
        } else {
          cancelAnimationFrame(frameId);
          height = heightElE.clientHeight;
          loadMore();
        }
      });
    };
    const loadMore = () => {
      if (
        scrollELE.scrollTop + windowHeight >=
        height + offsetTop + paddingBottom + marginBottom - 2
      ) {
        Binding.value();
      }
    };
  },
};
